import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error, r2_score
from src.models.database import db, HistoricalData, PredictionTask, PredictionResult
from src.services.llm_service import LLMService
import json
import threading
from datetime import datetime
import time

class EnhancedPredictionService:
    """增强版预测分析服务 - 融合客户算法和计算公式"""
    
    def __init__(self):
        self.llm_service = LLMService()
        self.running_tasks = {}
        
        # 客户提供的分析框架权重配置
        self.analysis_weights = {
            'industry_competitor_growth': 0.50,    # 行业平均增速、竞争对手增速：占比50%
            'historical_growth': 0.15,             # 本单位前三年平均增速、同比增速：占比15%
            'market_stage_expectation': 0.25,      # 市场所处阶段及未来影响业绩的预期：占比25%
            'group_development': 0.10              # 集团发展分解：占比10%
        }
    
    def start_prediction_task(self, task_id):
        """启动预测任务（异步）"""
        def run_task():
            try:
                self._execute_prediction_task(task_id)
            except Exception as e:
                self._handle_task_error(task_id, str(e))
        
        # 在新线程中运行任务
        thread = threading.Thread(target=run_task)
        thread.daemon = True
        thread.start()
        
        self.running_tasks[task_id] = thread
        
    def _execute_prediction_task(self, task_id):
        """执行预测任务"""
        task = PredictionTask.query.filter_by(task_id=task_id).first()
        if not task:
            raise ValueError(f"任务不存在: {task_id}")
        
        try:
            # 更新任务状态
            task.status = 'running'
            task.started_at = datetime.utcnow()
            task.progress = 0
            task.current_step = '准备数据'
            db.session.commit()
            
            # 获取任务参数
            company_ids = json.loads(task.company_ids)
            product_ids = json.loads(task.product_ids) if task.product_ids else []
            prediction_years = json.loads(task.prediction_years)
            
            # 步骤1: 准备历史数据
            historical_data = self._prepare_historical_data(company_ids, product_ids)
            task.progress = 20
            task.current_step = '构建预测模型'
            db.session.commit()
            
            # 步骤2: 构建和训练预测模型
            models = self._build_prediction_models(historical_data)
            task.progress = 40
            task.current_step = '生成预测结果'
            db.session.commit()
            
            # 步骤3: 生成预测结果
            predictions = self._generate_predictions(models, historical_data, prediction_years)
            task.progress = 60
            task.current_step = '应用客户分析框架'
            db.session.commit()
            
            # 步骤4: 应用客户分析框架和权重
            predictions_with_framework = self._apply_customer_analysis_framework(predictions, historical_data)
            task.progress = 70
            task.current_step = '计算三大核心指标'
            db.session.commit()
            
            # 步骤5: 计算三大核心指标
            predictions_with_core_metrics = self._calculate_core_business_metrics(predictions_with_framework)
            task.progress = 80
            task.current_step = '计算差异分析'
            db.session.commit()
            
            # 步骤6: 计算差异分析
            predictions_with_variance = self._calculate_variance_analysis(predictions_with_core_metrics, historical_data)
            task.progress = 90
            task.current_step = 'AI影响因素分析'
            db.session.commit()
            
            # 步骤7: LLM影响因素分析
            predictions_with_ai = self._generate_ai_analysis(predictions_with_variance, historical_data)
            task.progress = 95
            task.current_step = '保存结果'
            db.session.commit()
            
            # 步骤8: 保存预测结果
            self._save_prediction_results(task_id, predictions_with_ai)
            
            # 完成任务
            task.status = 'completed'
            task.progress = 100
            task.current_step = '任务完成'
            task.completed_at = datetime.utcnow()
            db.session.commit()
            
        except Exception as e:
            task.status = 'failed'
            task.error_message = str(e)
            task.completed_at = datetime.utcnow()
            db.session.commit()
            raise e
    
    def _prepare_historical_data(self, company_ids, product_ids):
        """准备历史数据"""
        query = HistoricalData.query.filter(HistoricalData.company_id.in_(company_ids))
        
        if product_ids:
            query = query.filter(HistoricalData.product_id.in_(product_ids))
        
        records = query.order_by(
            HistoricalData.company_id,
            HistoricalData.product_id,
            HistoricalData.year
        ).all()
        
        # 转换为DataFrame
        data = []
        for record in records:
            data.append({
                'company_id': record.company_id,
                'company_name': record.company_name,
                'product_id': record.product_id,
                'product_name': record.product_name,
                'year': record.year,
                'sales_volume': record.sales_volume,
                'avg_price': record.avg_price,
                'sales_amount': record.sales_amount,
                'unit_cost': record.unit_cost,
                'unit_profit': record.unit_profit,
                'yoy_growth_rate': record.yoy_growth_rate or 0,
                'cagr': record.cagr or 0
            })
        
        return pd.DataFrame(data)
    
    def _build_prediction_models(self, historical_data):
        """构建预测模型"""
        models = {}
        
        # 按产品分组构建模型
        for (company_id, product_id), group in historical_data.groupby(['company_id', 'product_id']):
            if len(group) < 3:  # 至少需要3年数据
                continue
            
            # 特征工程
            features = self._create_features(group)
            
            if len(features) < 2:
                continue
            
            # 构建多个目标变量的模型
            targets = ['sales_volume', 'avg_price', 'sales_amount', 'unit_cost', 'unit_profit']
            product_models = {}
            
            for target in targets:
                try:
                    X = features.drop(columns=[target] + ['year'])
                    y = features[target]
                    
                    if len(X) < 2:
                        continue
                    
                    # 训练模型
                    model = RandomForestRegressor(n_estimators=100, random_state=42)
                    model.fit(X, y)
                    
                    # 计算模型准确率
                    y_pred = model.predict(X)
                    accuracy = r2_score(y, y_pred)
                    
                    product_models[target] = {
                        'model': model,
                        'scaler': StandardScaler().fit(X),
                        'feature_names': X.columns.tolist(),
                        'accuracy': accuracy
                    }
                    
                except Exception as e:
                    print(f"构建模型失败 {company_id}-{product_id}-{target}: {str(e)}")
                    continue
            
            if product_models:
                models[(company_id, product_id)] = product_models
        
        return models
    
    def _create_features(self, group_data):
        """创建特征"""
        df = group_data.copy().sort_values('year')
        
        # 滞后特征
        for col in ['sales_volume', 'avg_price', 'sales_amount', 'unit_cost', 'unit_profit']:
            df[f'{col}_lag1'] = df[col].shift(1)
            df[f'{col}_lag2'] = df[col].shift(2)
        
        # 移动平均特征
        for col in ['sales_volume', 'avg_price', 'sales_amount']:
            df[f'{col}_ma2'] = df[col].rolling(window=2).mean()
            df[f'{col}_ma3'] = df[col].rolling(window=3).mean()
        
        # 趋势特征
        df['year_trend'] = df['year'] - df['year'].min()
        
        # 删除包含NaN的行
        df = df.dropna()
        
        return df
    
    def _apply_customer_analysis_framework(self, predictions, historical_data):
        """应用客户分析框架和权重"""
        for prediction in predictions:
            try:
                # 获取该产品的历史数据
                product_history = historical_data[
                    (historical_data['company_id'] == prediction['company_id']) & 
                    (historical_data['product_id'] == prediction['product_id'])
                ]
                
                if len(product_history) < 3:
                    continue
                
                # 1. 行业平均增速、竞争对手增速（占比50%）
                industry_growth_factor = self._calculate_industry_growth_factor(product_history)
                
                # 2. 本单位前三年平均增速、同比增速（占比15%）
                historical_growth_factor = self._calculate_historical_growth_factor(product_history)
                
                # 3. 市场所处阶段及未来影响业绩的预期（占比25%）
                market_stage_factor = self._calculate_market_stage_factor(product_history)
                
                # 4. 集团发展分解（占比10%）
                group_development_factor = self._calculate_group_development_factor(product_history)
                
                # 应用权重计算综合调整因子
                weighted_adjustment = (
                    industry_growth_factor * self.analysis_weights['industry_competitor_growth'] +
                    historical_growth_factor * self.analysis_weights['historical_growth'] +
                    market_stage_factor * self.analysis_weights['market_stage_expectation'] +
                    group_development_factor * self.analysis_weights['group_development']
                )
                
                # 应用调整因子到预测结果
                prediction['customer_framework_adjustment'] = weighted_adjustment
                prediction['adjusted_sales_volume'] = prediction['predicted_sales_volume'] * (1 + weighted_adjustment)
                prediction['adjusted_sales_amount'] = prediction['predicted_sales_amount'] * (1 + weighted_adjustment)
                
                # 记录各因素贡献
                prediction['framework_analysis'] = {
                    'industry_competitor_growth': {
                        'factor': industry_growth_factor,
                        'weight': self.analysis_weights['industry_competitor_growth'],
                        'contribution': industry_growth_factor * self.analysis_weights['industry_competitor_growth']
                    },
                    'historical_growth': {
                        'factor': historical_growth_factor,
                        'weight': self.analysis_weights['historical_growth'],
                        'contribution': historical_growth_factor * self.analysis_weights['historical_growth']
                    },
                    'market_stage_expectation': {
                        'factor': market_stage_factor,
                        'weight': self.analysis_weights['market_stage_expectation'],
                        'contribution': market_stage_factor * self.analysis_weights['market_stage_expectation']
                    },
                    'group_development': {
                        'factor': group_development_factor,
                        'weight': self.analysis_weights['group_development'],
                        'contribution': group_development_factor * self.analysis_weights['group_development']
                    },
                    'total_weighted_adjustment': weighted_adjustment
                }
                
            except Exception as e:
                print(f"应用客户分析框架失败: {str(e)}")
                prediction['customer_framework_adjustment'] = 0
                prediction['adjusted_sales_volume'] = prediction['predicted_sales_volume']
                prediction['adjusted_sales_amount'] = prediction['predicted_sales_amount']
        
        return predictions
    
    def _calculate_industry_growth_factor(self, product_history):
        """计算行业平均增速、竞争对手增速因子"""
        try:
            # 这里应该从行业数据中获取，目前使用模拟数据
            # 实际应用中需要接入行业数据库或API
            industry_avg_growth = 0.08  # 假设行业平均增速8%
            competitor_growth = 0.10    # 假设竞争对手增速10%
            
            # 计算相对于行业的增长因子
            company_growth = product_history['sales_amount'].pct_change().mean()
            industry_factor = (company_growth - industry_avg_growth) / industry_avg_growth
            competitor_factor = (company_growth - competitor_growth) / competitor_growth
            
            return (industry_factor + competitor_factor) / 2
            
        except Exception as e:
            print(f"计算行业增长因子失败: {str(e)}")
            return 0.0
    
    def _calculate_historical_growth_factor(self, product_history):
        """计算本单位前三年平均增速、同比增速因子"""
        try:
            if len(product_history) < 3:
                return 0.0
            
            # 前三年平均增速
            three_year_growth = (product_history['sales_amount'].iloc[-1] / product_history['sales_amount'].iloc[0]) ** (1/3) - 1
            
            # 同比增速（最新一年）
            yoy_growth = product_history['sales_amount'].pct_change().iloc[-1]
            
            # 综合因子
            return (three_year_growth + yoy_growth) / 2
            
        except Exception as e:
            print(f"计算历史增长因子失败: {str(e)}")
            return 0.0
    
    def _calculate_market_stage_factor(self, product_history):
        """计算市场所处阶段及未来影响业绩的预期因子"""
        try:
            # 基于历史数据判断市场阶段
            if len(product_history) < 2:
                return 0.0
            
            # 计算增长趋势
            growth_trend = product_history['sales_amount'].pct_change().mean()
            
            # 判断市场阶段（成长期、成熟期、衰退期）
            if growth_trend > 0.15:  # 高速成长期
                market_stage_factor = 0.20
            elif growth_trend > 0.05:  # 成长期
                market_stage_factor = 0.10
            elif growth_trend > -0.05:  # 成熟期
                market_stage_factor = 0.00
            else:  # 衰退期
                market_stage_factor = -0.10
            
            return market_stage_factor
            
        except Exception as e:
            print(f"计算市场阶段因子失败: {str(e)}")
            return 0.0
    
    def _calculate_group_development_factor(self, product_history):
        """计算集团发展分解因子"""
        try:
            # 这里应该从集团战略数据中获取，目前使用模拟数据
            # 实际应用中需要接入集团战略数据库
            group_strategy_factor = 0.05  # 假设集团战略支持度5%
            
            return group_strategy_factor
            
        except Exception as e:
            print(f"计算集团发展因子失败: {str(e)}")
            return 0.0
    
    def _calculate_core_business_metrics(self, predictions):
        """计算三大核心指标"""
        for prediction in predictions:
            try:
                # 1. 营业收入 = 主营业务收入 + 其它业务收入
                # 主营业务收入 = 销售本单位产品获得的收入
                main_business_revenue = prediction['adjusted_sales_amount']  # 主营业务收入
                other_business_revenue = main_business_revenue * 0.05  # 假设其它业务收入占主营业务5%
                total_revenue = main_business_revenue + other_business_revenue
                
                # 2. 净利润 = 收入 - 成本 - 费用 - 所得税
                total_cost = prediction['adjusted_sales_volume'] * prediction['predicted_unit_cost']  # 总成本
                operating_expenses = total_revenue * 0.15  # 假设运营费用占收入15%
                income_tax_rate = 0.25  # 假设所得税率25%
                income_tax = (total_revenue - total_cost - operating_expenses) * income_tax_rate
                net_profit = total_revenue - total_cost - operating_expenses - income_tax
                
                # 3. 自营出口收入 = 本单位产品直接销售到境外国家或地区的收入
                # 不包括销售给国内外贸公司转出口的产品收入
                export_ratio = 0.20  # 假设出口比例20%
                direct_export_revenue = main_business_revenue * export_ratio
                
                # 保存三大核心指标
                prediction['core_business_metrics'] = {
                    'total_revenue': {
                        'value': total_revenue,
                        'breakdown': {
                            'main_business_revenue': main_business_revenue,
                            'other_business_revenue': other_business_revenue
                        },
                        'formula': '主营业务收入 + 其它业务收入'
                    },
                    'net_profit': {
                        'value': net_profit,
                        'breakdown': {
                            'total_revenue': total_revenue,
                            'total_cost': total_cost,
                            'operating_expenses': operating_expenses,
                            'income_tax': income_tax
                        },
                        'formula': '收入 - 成本 - 费用 - 所得税'
                    },
                    'direct_export_revenue': {
                        'value': direct_export_revenue,
                        'breakdown': {
                            'export_ratio': export_ratio,
                            'base_revenue': main_business_revenue
                        },
                        'formula': '本单位产品直接销售到境外国家或地区的收入'
                    }
                }
                
                # 计算关键比率
                prediction['key_ratios'] = {
                    'profit_margin': net_profit / total_revenue if total_revenue > 0 else 0,  # 净利率
                    'cost_ratio': total_cost / total_revenue if total_revenue > 0 else 0,     # 成本率
                    'export_ratio': direct_export_revenue / total_revenue if total_revenue > 0 else 0  # 出口比例
                }
                
            except Exception as e:
                print(f"计算三大核心指标失败: {str(e)}")
                # 设置默认值
                prediction['core_business_metrics'] = {
                    'total_revenue': {'value': 0, 'breakdown': {}, 'formula': ''},
                    'net_profit': {'value': 0, 'breakdown': {}, 'formula': ''},
                    'direct_export_revenue': {'value': 0, 'breakdown': {}, 'formula': ''}
                }
                prediction['key_ratios'] = {
                    'profit_margin': 0,
                    'cost_ratio': 0,
                    'export_ratio': 0
                }
        
        return predictions
    
    def _generate_predictions(self, models, historical_data, prediction_years):
        """生成预测结果"""
        predictions = []
        
        for (company_id, product_id), product_models in models.items():
            # 获取该产品的历史数据
            product_data = historical_data[
                (historical_data['company_id'] == company_id) & 
                (historical_data['product_id'] == product_id)
            ].copy()
            
            if len(product_data) == 0:
                continue
            
            # 获取最新年份的数据作为基准
            latest_data = product_data.iloc[-1]
            
            for year in prediction_years:
                year = int(year)
                
                # 创建预测特征
                prediction_features = self._create_prediction_features(
                    product_data, latest_data, year
                )
                
                # 对每个目标变量进行预测
                prediction_result = {
                    'company_id': company_id,
                    'company_name': latest_data['company_name'],
                    'product_id': product_id,
                    'product_name': latest_data['product_name'],
                    'prediction_year': year
                }
                
                confidence_scores = []
                
                for target, model_info in product_models.items():
                    try:
                        model = model_info['model']
                        feature_names = model_info['feature_names']
                        
                        # 确保特征顺序一致
                        X_pred = prediction_features[feature_names].values.reshape(1, -1)
                        
                        # 预测
                        pred_value = model.predict(X_pred)[0]
                        
                        # 确保预测值为正数
                        pred_value = max(pred_value, 0)
                        
                        prediction_result[f'predicted_{target}'] = pred_value
                        confidence_scores.append(model_info['accuracy'])
                        
                    except Exception as e:
                        print(f"预测失败 {company_id}-{product_id}-{target}: {str(e)}")
                        # 使用历史平均值作为备选
                        avg_value = product_data[target].mean()
                        prediction_result[f'predicted_{target}'] = avg_value
                        confidence_scores.append(0.5)
                
                # 计算平均置信度
                prediction_result['confidence_score'] = np.mean(confidence_scores) if confidence_scores else 0.5
                
                predictions.append(prediction_result)
        
        return predictions
    
    def _create_prediction_features(self, historical_data, latest_data, prediction_year):
        """创建预测特征"""
        # 基于最新数据创建特征
        features = {}
        
        # 滞后特征（使用最新年份的数据）
        for col in ['sales_volume', 'avg_price', 'sales_amount', 'unit_cost', 'unit_profit']:
            features[f'{col}_lag1'] = latest_data[col]
            if len(historical_data) >= 2:
                features[f'{col}_lag2'] = historical_data.iloc[-2][col]
            else:
                features[f'{col}_lag2'] = latest_data[col]
        
        # 移动平均特征
        for col in ['sales_volume', 'avg_price', 'sales_amount']:
            if len(historical_data) >= 2:
                features[f'{col}_ma2'] = historical_data[col].tail(2).mean()
            else:
                features[f'{col}_ma2'] = latest_data[col]
            
            if len(historical_data) >= 3:
                features[f'{col}_ma3'] = historical_data[col].tail(3).mean()
            else:
                features[f'{col}_ma3'] = latest_data[col]
        
        # 趋势特征
        min_year = historical_data['year'].min()
        features['year_trend'] = prediction_year - min_year
        
        return pd.Series(features)
    
    def _calculate_variance_analysis(self, predictions, historical_data):
        """计算差异分析"""
        for prediction in predictions:
            try:
                # 获取基准年份（最新年份）的数据
                base_data = historical_data[
                    (historical_data['company_id'] == prediction['company_id']) & 
                    (historical_data['product_id'] == prediction['product_id'])
                ].iloc[-1]
                
                # 计算各种差异
                # 量差 = (预测销量 - 基准销量) * 基准单价
                volume_diff = prediction['adjusted_sales_volume'] - base_data['sales_volume']
                prediction['volume_variance'] = volume_diff * base_data['avg_price']
                
                # 价差 = (预测单价 - 基准单价) * 预测销量
                price_diff = prediction['predicted_avg_price'] - base_data['avg_price']
                prediction['price_variance'] = price_diff * prediction['adjusted_sales_volume']
                
                # 成本差异 = (预测成本 - 基准成本) * 预测销量
                cost_diff = prediction['predicted_unit_cost'] - base_data['unit_cost']
                prediction['cost_variance'] = -cost_diff * prediction['adjusted_sales_volume']  # 成本增加为负影响
                
                # 总差异
                prediction['total_variance'] = (
                    prediction['volume_variance'] + 
                    prediction['price_variance'] + 
                    prediction['cost_variance']
                )
                
            except Exception as e:
                print(f"计算差异分析失败: {str(e)}")
                # 设置默认值
                prediction['volume_variance'] = 0
                prediction['price_variance'] = 0
                prediction['cost_variance'] = 0
                prediction['total_variance'] = 0
        
        return predictions
    
    def _generate_ai_analysis(self, predictions, historical_data):
        """生成AI影响因素分析"""
        for prediction in predictions:
            try:
                # 获取该产品的历史数据
                product_history = historical_data[
                    (historical_data['company_id'] == prediction['company_id']) & 
                    (historical_data['product_id'] == prediction['product_id'])
                ]
                
                # 构建分析上下文
                context = {
                    'product_name': prediction['product_name'],
                    'company_name': prediction['company_name'],
                    'prediction_year': prediction['prediction_year'],
                    'historical_trend': self._analyze_historical_trend(product_history),
                    'prediction_summary': {
                        'sales_volume': prediction['adjusted_sales_volume'],
                        'avg_price': prediction['predicted_avg_price'],
                        'sales_amount': prediction['adjusted_sales_amount'],
                        'unit_cost': prediction['predicted_unit_cost'],
                        'unit_profit': prediction['predicted_unit_profit']
                    },
                    'variance_analysis': {
                        'volume_variance': prediction['volume_variance'],
                        'price_variance': prediction['price_variance'],
                        'cost_variance': prediction['cost_variance'],
                        'total_variance': prediction['total_variance']
                    },
                    'customer_framework': prediction.get('framework_analysis', {}),
                    'core_metrics': prediction.get('core_business_metrics', {})
                }
                
                # 调用LLM生成分析
                analysis = self.llm_service.generate_influence_factors_analysis(context)
                prediction['influence_factors_analysis'] = analysis
                
                # 模拟延时
                time.sleep(0.5)
                
            except Exception as e:
                print(f"生成AI分析失败: {str(e)}")
                # 生成默认分析
                prediction['influence_factors_analysis'] = self._generate_default_analysis(prediction)
        
        return predictions
    
    def _analyze_historical_trend(self, product_history):
        """分析历史趋势"""
        if len(product_history) < 2:
            return "数据不足"
        
        # 计算趋势
        sales_trend = product_history['sales_amount'].pct_change().mean() * 100
        volume_trend = product_history['sales_volume'].pct_change().mean() * 100
        price_trend = product_history['avg_price'].pct_change().mean() * 100
        
        return {
            'sales_growth_rate': round(sales_trend, 2),
            'volume_growth_rate': round(volume_trend, 2),
            'price_growth_rate': round(price_trend, 2),
            'years_of_data': len(product_history)
        }
    
    def _generate_default_analysis(self, prediction):
        """生成默认分析"""
        return f"""基于历史数据和预测模型分析，{prediction['product_name']}在{prediction['prediction_year']}年的预测结果如下：

销售预测：预计销售额达到{prediction['adjusted_sales_amount']:.1f}万元，销售量{prediction['adjusted_sales_volume']:.0f}单位。

主要影响因素：
1. 市场需求变化：基于历史趋势分析，市场需求呈现稳定增长态势
2. 价格策略：平均销售单价预计为{prediction['predicted_avg_price']:.2f}元
3. 成本控制：单位成本预计为{prediction['predicted_unit_cost']:.2f}元

差异分析：总差异为{prediction['total_variance']:.1f}万元，主要来源于量差和价差的综合影响。

建议关注市场变化和成本控制，以确保预测目标的实现。"""
    
    def _save_prediction_results(self, task_id, predictions):
        """保存预测结果"""
        for prediction in predictions:
            result = PredictionResult(
                task_id=task_id,
                company_id=prediction['company_id'],
                company_name=prediction['company_name'],
                product_id=prediction['product_id'],
                product_name=prediction['product_name'],
                prediction_year=prediction['prediction_year'],
                predicted_sales_volume=prediction['adjusted_sales_volume'],
                predicted_avg_price=prediction['predicted_avg_price'],
                predicted_sales_amount=prediction['adjusted_sales_amount'],
                predicted_unit_cost=prediction['predicted_unit_cost'],
                predicted_unit_profit=prediction['predicted_unit_profit'],
                volume_variance=prediction['volume_variance'],
                price_variance=prediction['price_variance'],
                cost_variance=prediction['cost_variance'],
                total_variance=prediction['total_variance'],
                influence_factors_analysis=prediction['influence_factors_analysis'],
                confidence_score=prediction['confidence_score']
            )
            
            db.session.add(result)
        
        db.session.commit()
    
    def _handle_task_error(self, task_id, error_message):
        """处理任务错误"""
        try:
            task = PredictionTask.query.filter_by(task_id=task_id).first()
            if task:
                task.status = 'failed'
                task.error_message = error_message
                task.completed_at = datetime.utcnow()
                db.session.commit()
        except Exception as e:
            print(f"处理任务错误失败: {str(e)}")
    
    def cancel_task(self, task_id):
        """取消任务"""
        if task_id in self.running_tasks:
            # 注意：Python线程无法强制终止，这里只是标记
            del self.running_tasks[task_id]
    
    def get_prediction_summary(self, task_id):
        """获取预测结果汇总"""
        try:
            task = PredictionTask.query.filter_by(task_id=task_id).first()
            if not task:
                raise ValueError("任务不存在")
            
            results = PredictionResult.query.filter_by(task_id=task_id).all()
            
            if not results:
                return {'task': task.to_dict(), 'summary': {}}
            
            # 计算汇总统计
            total_predicted_sales = sum(r.predicted_sales_amount for r in results)
            avg_confidence = sum(r.confidence_score for r in results) / len(results)
            total_variance = sum(r.total_variance for r in results)
            
            summary = {
                'total_products': len(results),
                'total_predicted_sales': round(total_predicted_sales, 2),
                'average_confidence': round(avg_confidence, 3),
                'total_variance': round(total_variance, 2),
                'prediction_years': list(set(r.prediction_year for r in results))
            }
            
            return {
                'task': task.to_dict(),
                'summary': summary,
                'results': [r.to_dict() for r in results]
            }
            
        except Exception as e:
            raise e
    
    def get_model_accuracy_stats(self):
        """获取模型准确率统计"""
        try:
            # 这里可以实现更复杂的准确率统计
            # 目前返回模拟数据
            return {
                'overall_accuracy': 0.925,
                'by_product_type': [
                    {'product_type': '药品', 'accuracy': 0.935},
                    {'product_type': '保健品', 'accuracy': 0.915},
                    {'product_type': '医疗器械', 'accuracy': 0.920}
                ],
                'by_prediction_horizon': [
                    {'years_ahead': 1, 'accuracy': 0.945},
                    {'years_ahead': 2, 'accuracy': 0.925},
                    {'years_ahead': 3, 'accuracy': 0.905}
                ]
            }
            
        except Exception as e:
            raise e
